﻿using MyLogProject;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using static System.Net.Mime.MediaTypeNames;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Pkcs;
using System.Xml;
using Org.BouncyCastle.Math;

namespace MyProjectControlApplication.EncrypAndDecryp
{
    /// <summary>
    /// 加解密控制类
    /// </summary>
    public class EncrypAndDecrypControl
    {
        public static string originalXmlKeys = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC+INwGC9dU/FqtU+iyNgkoXek4Il1frqDVBzt1xOKCszBCCg1Vc3ILAVCNELm0KrT8eZT4Qed8Pk9qIjE+rjDXOs3qfEyJEcw4UyS/8LXuaOK6Fk77K3yILCqrIHYnD/5R/YlzN3JZUBc9XuCwBE79vFQz1YFkVOqnPeH0evL0hN2MBgn6A3ExDUA/G8wH6+rISvpWaxL13fXtLOzOdW9GEPbUebNgyBrlq/bET3pAtZm8DidveRF5tWlW8TvnPmiRRedIp9be2avExtJx6T52k+fpYaaZmpzAC3cSQJumRgakzkDN3+KnMJlJgxE1kceaPZFArvtG079AxVk+dW2BAgMBAAECggEANZa9bVbZErMuO7xy0gg4/I+7tH67IsTtwB2RvNgJoB0xdOuwZm1rr35nXdtg/E8tRBxgyLiKrpJBgACzMJ+YVJHWiEkQqXHCxf1pVlBadyBJB3pSOKlBKICKZkF4C/qODD4SB8+RA2t3oWykl/ge65Wxhgqftc/Zc9oVXftpj1GHIfrl4dXT960Wsq/Qro+MB54YsSeglXfWm2OmgLsUufWQaz6m9cNHFtt+TIeipTspRYMia62CPmxkgx7DVmbEhZyeq2+tylawIfRsB00CGBSlp5u9WzL5H60JTLh/z4M0s6mBDKF+oPOdP71FbcZchpyok9McpkIOHn8b14CJIQKBgQDrGgskp9KYrmgSk+skGp9sYpcNrcNUuXYWEwAYo+fbQtQaNtSSb8AkUmTx6pQkU9WSvxDM5dqfc4tfj0KotePRBGgD9vpuLSnMcWdgI7d+ys0BaEWrL8bvswQbzw14qVRBpSGl9EJXNO14alMPJ29mPT3lZ4QT9ZhKHfiZp/KRewKBgQDPB2fFxKsqls8cJ38bCHV63GppuyqL1IOlfVhf6chf8cygvAlTNy5eNaq7Hw3yEwuCYLZJXn3EdQ25vP4zjQO9aEN/M8PmD4hB4XIZx3jogv56WLutfHLTfHql9wG8iyZDhIWfwRPow/FUtnaPmDn2v29wowL7zzL4goT7lo+2MwKBgQDEu1lhxhGjdCZgjWjyIFkRwHp4ltRifIOFO0cUV2v4fbaxbPp6w4q8mjogedSXhZOtpbbwTtOgJHcXcvEr7nECAjbsQmsTcTWN/8Oqnpi5QAlGyTOraWKGSH4Cq0OxmbiI6h77GSe+g+rHnel9P9mna031Pqc2cIiMVQInynNgKwKBgGE/qEZlIMZLuxQNlY5cRdslqLLr4Yt3kzNsktPTHHW9PpMOYQ7+77//U6i8aK+atKBUz6vdQBTFq2HhXkNW7TfOv04EQfRSvX286f0kDy6hQeq0vcw7ljCz22UUh3NKpfm3SZGGf9SqHjXd1AmVxzyaJj3xxNgGN3o2zULlMbKzAoGBAIN2/hnuzcGBPZZq0pNhA1lBmAZOiIUMh1XaaH5MNj+BvspsHQApIKPQLtyT1CWZ7ZdJoKQ016HxGUSJXGC4TaT/qtaAqWFDIMCDXApEYffD5RBbi4DjYG2kBjRWl6x9oq0yvTlphlCFJobtQMT/GF8ICGurtKeRh78o5G/H51yF";


        #region RSA 的密钥产生

        /// <summary>
        /// RSA产生密钥
        /// </summary>
        /// <param name="xmlKeys">私钥</param>
        /// <param name="xmlPublicKey">公钥</param>
        public void RSAKey(ref string xmlKeys, ref string xmlPublicKey)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                xmlKeys = rsa.ToXmlString(true);
                xmlPublicKey = rsa.ToXmlString(false);
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "RSAEncrypt", ex.ToString());
            }
        }
        #endregion

        /// <summary>
        /// RSA的加密函数
        /// </summary>
        /// <param name="xmlPublicKey">公钥</param>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns></returns>
        public string RSAEncrypt(string xmlPublicKey, string encryptString)
        {
            string Result = null;
            try
            {
                byte[] PlainTextBArray;
                byte[] CypherTextBArray;
                string xmlKeys = RSAPrivateKeyDotNet2Java(xmlPublicKey);               
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlKeys);
                PlainTextBArray = (new UnicodeEncoding()).GetBytes(encryptString);
                CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
                Result = Convert.ToBase64String(CypherTextBArray);
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "RSAEncrypt", ex.ToString());
            }
            return Result;
        }

        /// <summary>
        /// RSA的加密函数 
        /// </summary>
        /// <param name="xmlPublicKey">公钥</param>
        /// <param name="EncryptString">待加密的字节数组</param>
        /// <returns></returns>
        public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
        {
            string Result = null;
            try
            {
                byte[] CypherTextBArray;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPublicKey);
                CypherTextBArray = rsa.Encrypt(EncryptString, false);
                Result = Convert.ToBase64String(CypherTextBArray);
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "RSAEncrypt", ex.ToString());
            }
            return Result;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlPrivateKey">私钥</param>
        /// <param name="decryptString">待解密字符串</param>
        /// <returns></returns>
        public static string RSADecrypt(string xmlPrivateKey, string decryptString)
        {
            string Result = null;
            try
            {
                byte[] PlainTextBArray;
                byte[] DypherTextBArray;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                PlainTextBArray = Convert.FromBase64String(decryptString);
                DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
                var tes = new UnicodeEncoding();
                Result = Encoding.Default.GetString(DypherTextBArray); // 解码
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "RSADecrypt", ex.ToString());
            }
            return Result; ;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlPrivateKey">私钥</param>
        /// <param name="DecryptString">待解密数组</param>
        /// <returns></returns>
        public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
        {
            string Result = null;
            try
            {
                byte[] DypherTextBArray;

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                DypherTextBArray = rsa.Decrypt(DecryptString, false);
                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "RSADecrypt", ex.ToString());
            }
            return Result;
        }
        public static string RSAPrivateKeyDotNet2Java(string privateKey)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(privateKey);
            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));

            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);

            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            return Convert.ToBase64String(serializedPrivateBytes);
        }

        public static string RSAPrivateKeyJavaToDotNet(string privateKey)
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));

            return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));

        }

        private string GetMD5(string _pwd)
        {
            string _md5Str = "";
            try
            {
                using (var md5Hasher = MD5.Create())
                {
                    byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(_pwd));

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < data.Length; i++)
                    {
                        sb.Append(data[i].ToString("x2"));
                    }
                    _md5Str = sb.ToString();
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetMD5", ex.ToString());
            }
            return _md5Str;
        }


       
    }
}
